# -*- coding: utf-8 -*-
from libkontrolcu import *
from dialogs import *
from os import stat
from os import path as Path

Controls = { 32 : hashlib.md5,
             40 : hashlib.sha1,
             56 : hashlib.sha224,
             64 : hashlib.sha256,
             96 : hashlib.sha384,
            128 : hashlib.sha512 }
ControlsText = { "md5" : hashlib.md5,
                "sha1" : hashlib.sha1,
              "sha224" : hashlib.sha224,
              "sha256" : hashlib.sha256,
              "sha384" : hashlib.sha384,
              "sha512" : hashlib.sha512 }

class PiFromCli:
    def __init__(self, ControlType="", FileList=[]):
        self.cType = ControlsText.get(ControlType)
        self.fileList = FileList
        self.message = {}
        self.result = []

    def GetRealSummary(self):
        finalresultsize = 0
        i=0
        while i<len(self.fileList):
            if Path.exists(self.fileList[i]):
                finalresultsize += stat(self.fileList[i]).st_size
                i += 1
            else:
                self.message[_("%s is missing.")% self.fileList[i]]="0"
                self.fileList.pop(i)

        if finalresultsize > ((1024**2)*50): #50 mb limitation
            checkdialog = CheckDialog(worklist=self.fileList, 
                                      finalnumber=finalresultsize)
            progressbar = checkdialog.progress
            thatlabel = checkdialog.filename
            cancelbutton = checkdialog.cancelbutton
            pi = ProgressIncrement(progressbar, 
                                   checktype=self.cType, 
                                   filelist=self.fileList, 
                                   label=thatlabel)

            def CloseDialog():
                self.result = pi.resultlist
                pi.quit()
                checkdialog.close()

            def terminateIt():
                pi.terminate()
                checkdialog.close()
                textdialog = TextDialog(message={_("Check is canceled by user!"):" "}) 
                textdialog.show()
                textdialog.exec_()
                quit()

	    QObject.connect(pi, SIGNAL("incrementProgressBar()"), pi.incrementProgressBar)
            QObject.connect(checkdialog.cancelbutton, SIGNAL("clicked(bool)"), terminateIt)
            QObject.connect(pi, SIGNAL("operationFinished()"), CloseDialog)

            pi.start()
	    checkdialog.exec_()

        else:
            for i in self.fileList:
                Object=CUnit(path=i)
                Object.CheckSum(self.cType)

                self.result.append(Object.ValueReal + "  " + Object.Name)

    def ControlFiles(self):
        self.GetRealSummary()

        for line in self.result:
            self.message[line]=" "

        textdialog = TextDialog(message=self.message)
        textdialog.show()
        textdialog.exec_()

    def CompareSummary(self, summaryValue):
        self.cType = Controls.get(len(summaryValue))

        self.GetRealSummary()
        realSummary, fileName = self.result[0].split("  ")

        if summaryValue == realSummary:
            self.message[_("Result: OK!")]="+"
        else:
            self.message[_("Result: Wrong!")]="-"

        textdialog = TextDialog(message=self.message)
        textdialog.show()
        textdialog.exec_()

    def CompareFromFile(self, File):
        FilesStatusTemp = FromFile(File)
        FilesStatus={}

        #Turning keys and values
        for i in FilesStatusTemp.keys():
            if FilesStatusTemp[i] == "0":
                FilesStatus[i] = FilesStatusTemp[i]
            else:
                FilesStatus[FilesStatusTemp[i]] = i

        for file in FilesStatus.keys():
            self.cType = Controls.get(len(FilesStatus[file]))
            if FilesStatus[file] != "0":
                self.fileList.append(file)
            else:
                self.message[_("%s is missing.")% file]="0"

        self.GetRealSummary()
        for line in self.result:
            realSummary, fileName = line.split("  ")

            for i in self.fileList:
                if fileName == i[-len(fileName):]:
                    fileName = i

            if realSummary == FilesStatus[fileName]:
                self.message[_("%s is OK.")% fileName]="+"
            else:
                self.message[_("%s is modified or changed.")% fileName]="-"

        textdialog = TextDialog(message=self.message)
        textdialog.show()
        textdialog.exec_()
